<template>
  <t-card :bordered="false">

    <!-- 自定义表格 -->
    <custom-table 
      ref="customTableRef" 
      row-key="id" 
      :columns="columns" 
      :api="homeProductData"
      :foot-data="footData"
      :on-before-set-data="handleTableSetData"
      max-height="calc(100vh - 280px)"
      fixed-page-size
      >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl); display: flex;">
          <t-radio-group v-model="defaultCompany" theme="button"  @change="handleInitTable" style="margin-right: 10px;">
            <t-radio-button :value="_.id" v-for="_ in companyList">{{ _.name }}</t-radio-button>
          </t-radio-group>
          <t-radio-group v-model="defaultCustomers"   @change="handleTimeChange">
            <t-radio-button v-for="_ in timeDate" :key="'report'+_.value" :value="_.value"> {{ _.name }}</t-radio-button>
          </t-radio-group>
           <t-date-range-picker enable-time-picker v-model="timeRange" allow-input clearable @change="onChange" style="margin-left: 10px;"/>
        </div>
      </template>
      <template #productDesignerId="{ row }">
        {{ userStore.getUserNameById(row.productDesignerId) }}
      </template>
      <template #addCount="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.addCount)">{{ row.addCount&&row.addCount.split(',').length }}</t-link>
      </template>
      <template #zhuanChanPin="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.zhuanChanPin)">{{ row.zhuanChanPin&&row.zhuanChanPin.split(',').length }}</t-link>
      </template>
      <template #jiDan="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.jiDan)">{{ row.jiDan&&row.jiDan.split(',').length }}</t-link>
      </template>
      <template #yiGui="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.yiGui)">{{ row.yiGui&&row.yiGui.split(',').length }}</t-link>
      </template>
      <template #yanShou="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.yanShou)">{{ row.yanShou&&row.yanShou.split(',').length }}</t-link>
      </template>
      <template #chuFangAn="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.chuFangAn)">{{ row.chuFangAn&&row.chuFangAn.split(',').length }}</t-link>
      </template>
      <template #baoJia="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.baoJia)">{{ row.baoJia&&row.baoJia.split(',').length }}</t-link>
      </template>
      <template #xiaDan="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.xiaDan)">{{ row.xiaDan&&row.xiaDan.split(',').length }}</t-link>
      </template>
      <template #fuChe="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.fuChe)">{{ row.fuChe&&row.fuChe.split(',').length }}</t-link>
      </template>
      <template #chuWeiGui="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.chuWeiGui)">{{ row.chuWeiGui&&row.chuWeiGui.split(',').length }}</t-link>
      </template>
      <template #contract="{ row }">
        <t-link theme="primary" @click="hanldeGoToDesignList(row.contract)">{{ row.contract&&row.contract.split(',').length }}</t-link>
      </template>
      <template #contractPercent="{ row }">
        <t-link>
          {{
      (row.contract || row.xiaDan || row.yiGui || row.chuWeiGui || row.yanShou)
        ? 
            (
              ((row.contract?row.contract.split(',').length:0 )+ 
              (row.xiaDan ? row.xiaDan.split(',').length : 0) + 
              (row.yiGui ? row.yiGui.split(',').length : 0) + 
              (row.chuWeiGui ? row.chuWeiGui.split(',').length : 0) + 
              (row.yanShou ? row.yanShou.split(',').length : 0)
            ) / 
            row.addCount.split(',').length * 100
          ).toFixed(2) + '%'
        : ''
    }}</t-link>
      </template>
      <template #deletedPercent="{ row }">
        <t-link>{{ row.deleted&&(row.deleted.split(',').length/row.addCount.split(',').length*100).toFixed(2) +'%'}}</t-link>
      </template>
      <template #contractPrice="{ row }">
        <t-link>{{ row.contractPrice&&row.contractPrice}}</t-link>
      </template>
      
      

    </custom-table>

  </t-card>
</template>

<script lang="ts">
export default {
  name: 'ReportProduct',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, onMounted, onUpdated, Ref, ref, useTemplateRef } from 'vue';

import { homeProductData } from '@/api/dashboard/base';
import { getCompanyList, getSimpleDeptList } from '@/api/system/dept';
import { propertyManageCRUD } from '@/api/config/property';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';

import { useDictionaryStore, useUserStore } from '@/store';
import { getUserListByRoleCode } from '@/api/system/user';
import listToTree from '@/utils/listToTree';
import disposableParams from '@/utils/disposableParams';
import { useRouter } from 'vue-router';
// 路由器
const router = useRouter();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// 公司列表
const companyList = ref([]);
// 默认公司
const defaultCompany = ref()
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = data;
      defaultCompany.value = data[0].id
      handleInitTable()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
const timeDate = [
  {value:1,name:'本周'},
  {value:2,name:'本月'},
  {value:3,name:'本年'},
  {value:4,name:'全部'},
  ]
// 时间默认
const defaultCustomers = ref(4)

const table = ref([])
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  table.value = data
  return data;
};

const hanldeGoToDesignList = (orderIds:string) => {
  if(!orderIds) return
  disposableParams.set('to-do-tree-jump-params', {
  
    orderIds: orderIds,
   
  });
  router.push({ path:'/order/product', query: { timeStamp: new Date().getTime() } });
}
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  {colKey:'id',title:'产品部',thClassName:'fw-b',children:[
    { colKey: 'productDesignerId', title: '产品设计师',align:'center' },
    { colKey: 'addCount', title: '新增',align:'center' },
    { colKey: 'jiDan', title: '积单',align:'center' },
    { colKey: 'zhuanChanPin', title: '转产品',align:'center' },
    { colKey: 'chuFangAn', title: '初方案',align:'center' },
    { colKey: 'fuChe', title: '复测',align:'center' },
    { colKey: 'baoJia', title: '报价',align:'center'},
    { colKey: 'contract', title: '合同',align:'center'},
    { colKey: 'xiaDan', title: '下单',align:'center'},
    { colKey: 'yiGui', title: '衣柜进场',align:'center'},
    { colKey: 'chuWeiGui', title: '橱、卫柜进场',align:'center'},
    { colKey: 'yanShou', title: '验收',align:'center'},
    { colKey: 'contractPrice', title: '累计产值',align:'center'},
    { colKey: 'contractPercent', title: '转化率',align:'center'},
  ]}
  
];
const handleSeachTable=(params:any) =>{
  disposableParams.set('to-do-tree-jump-params', {
    orderIds: '',
  });
  handleInitTable()
}
// 处理初始化表格
const handleInitTable = () => {
  // 待办树跳转参数
  const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
  const params = {
    beginTime:'',
    endTime:'',
    companyId:defaultCompany.value
  }
  const now = new Date();
  
  switch(defaultCustomers.value) {
    case 1: // 本周
      const firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)));
      const lastDayOfWeek = new Date(firstDayOfWeek);
      lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
      
      params.beginTime = dayjs(firstDayOfWeek).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfWeek).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 2: // 本月
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      params.beginTime = dayjs(firstDayOfMonth).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfMonth).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 3: // 本年
      const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
      const lastDayOfYear = new Date(now.getFullYear(), 11, 31);
      
      params.beginTime = dayjs(firstDayOfYear).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfYear).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 4: // 全部
      // 不传日期参数
      params.beginTime='';
      params.endTime='';
      break;
  }
  if(timeRange.value.length>0) {
     params.beginTime=timeRange.value[0];
    params.endTime=timeRange.value[1];
  }
  customTableRef.value.initTable(params);
};
const handleTimeChange = () => {
  timeRange.value = []
  handleInitTable()
}
// 日期选择
const timeRange = ref([])
const onChange = (value, context) => {
  const params = {
    beginTime:'',
    endTime:'',
    companyId:defaultCompany.value
  }
  if(value.length>0) {
    params.beginTime=value[0];
    params.endTime=value[1];
    defaultCustomers.value = 0
  } else {
    params.beginTime='';
    params.endTime='';
    defaultCustomers.value = 4
  }
  customTableRef.value.initTable(params);
}
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleGetCompanyList();
});
// onUpdated(() => {
//   handleRefreshTable();
// })
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 计算汇总值
const calculateSummary = (colKey: string) => {
  if (!table.value.length) return 0;
  
  // 处理计数字段（如新增数、有效数等）
  if (['addCount', 'yiGui','zhuanChanPin', 'chuWeiGui','chuFangAn','baoJia', 'contract', 'yanShou', 'fuChe', 'xiaDan', 'jiDan'].includes(colKey)) {
    return table.value.reduce((sum, row) => sum + (row[colKey] ? row[colKey].split(',').length : 0), 0);
  }
  
  // 处理百分比字段（如有效率、转设计率等）
  if (colKey.endsWith('Percent')) {
    const baseField = colKey.replace('Percent', '');
    const countField = 'addCount';
    const total = table.value.reduce((sum, row) => sum + (row[countField] ? row[countField].split(',').length : 0), 0);
    const contractpart = table.value.reduce((sum, row) => sum + (row[baseField] ? row[baseField].split(',').length : 0), 0);
    const xiaDanpart = table.value.reduce((sum, row) => sum + (row['xiaDan'] ? row['xiaDan'].split(',').length : 0), 0);
    const yiGuipart = table.value.reduce((sum, row) => sum + (row['yiGui'] ? row['yiGui'].split(',').length : 0), 0);
    const chuWeiGuipart = table.value.reduce((sum, row) => sum + (row['chuWeiGui'] ? row['chuWeiGui'].split(',').length : 0), 0);
    const yanShoupart = table.value.reduce((sum, row) => sum + (row['yanShou'] ? row['yanShou'].split(',').length : 0), 0);
    const part = contractpart+xiaDanpart+yiGuipart+chuWeiGuipart+yanShoupart
    return total > 0 ? (part / total * 100).toFixed(2) + '%' : '0%';
  }
  
  // 处理金额字段
  if (colKey === 'contractPrice') {
    return table.value.reduce((sum, row) => sum + (parseFloat(row[colKey]) || 0), 0).toFixed(2);
  }
  
  return 0;
};
// 普通表尾数据
const footData = computed(() => {
  return [
    {
      productDesignerId: '汇总',
      addCount: calculateSummary('addCount'),
      jiDan: calculateSummary('jiDan'),
      zhuanChanPin: calculateSummary('zhuanChanPin'),
      chuWeiGui: calculateSummary('chuWeiGui'),
      baoJia: calculateSummary('baoJia'),
      chuFangAn: calculateSummary('chuFangAn'),
      yanShou: calculateSummary('yanShou'),
      contract: calculateSummary('contract'),
      yiGui: calculateSummary('yiGui'),
      fuChe: calculateSummary('fuChe'),
      xiaDan: calculateSummary('xiaDan'),
      contractPrice: calculateSummary('contractPrice'),
      contractPercent: calculateSummary('contractPercent'),
    },
  ];
});
</script>

<style lang="less" scoped>
:deep(.fw-b) {
  font-weight: bold;
}
</style>
